package com.aios.action.user.system;

import com.aios.service.ExistValidationEnum;
import com.aios.util.EmailUtil;

public class SystemUserSaveAction extends AbstractSystemUserAction {
	
	private static final long serialVersionUID = 1L;
	
	public String execute() {

		validateSystemUser();
		
		if(hasErrors())	{
			return INPUT;
		}
		
		if(!(EmailUtil.chackEmailPattern(systemUser.getEmail()))) {
			addActionError(getText("error.email.invalid"));
			return INPUT;
		}
		
		if(getMode() == Mode.ADD) {
			ExistValidationEnum existValidationEnum = 
					systemUserService.emailExistValidation(systemUser.getEmail());
			
			if(existValidationEnum != ExistValidationEnum.NOT_EXIST) {
				addActionError(getText("error.email.exist"));
				return INPUT;
			}
			
			try {
				systemUserService.saveWithPasswordRecords(systemUser,getSessionUserVariable().getId());
				
			}catch (Exception e) {
				e.printStackTrace();
				addActionError(getText("error.insert"));
				return INPUT;
			}
			
		} else if(getMode() == Mode.EDIT) {
			try {
				ExistValidationEnum existValidationEnum = 
						systemUserService.emailExistValidation(systemUser.getEmail(),systemUser.getId());
				
				if(existValidationEnum != ExistValidationEnum.NOT_EXIST) {
					addActionError(getText("error.email.exist"));
					return INPUT;
				}
				systemUserService.update(systemUser,getSessionUserVariable().getId());
			} catch (Exception e) {
				//add action error
				addActionError(getText("error.update"));
				return INPUT;
			}
			//validation
		} else {
			//add action error
			return INPUT;
		}
		
		return SUCCESS;
	}

	private void validateSystemUser() {
		
		if(systemUser.getName().isEmpty()) {
			addFieldError("systemUser.name", getText("error.name.empty"));
		}
		
		if(systemUser.getEmail().isEmpty()) {
			addFieldError("systemUser.email", getText("error.email.empty"));
		}
		
		if(systemUser.getUserPassword().isEmpty()) {
			addFieldError("systemUser.password", getText("error.password.empty"));
		}
		
	}
}
